import { defineComponent, reactive, DefineComponent, markRaw, watch } from 'vue'
import { AppNavigator } from './app-navigator'

// app-navigator-page 组件
// 从实现上看，defineComponent 只返回传递给它的对象。
export const AppNavigatorPage = defineComponent({
  setup() {
    const state = reactive({
      PageComponent: null as null | DefineComponent
    })
    const navigator = AppNavigator.use.inject()

    // 根据 route.path 变化来动态加载对应的组件
    const utils = {
      reset: async () => {
        let { path } = navigator.state.route

        if (!path) {
          return
        }
        if (path.charAt(0) === '/') {
          path = path.slice(1)
        }
        //动态加载对应的组件 因加载的是es模块，需要用default
        const Component = (await import('story/pages/' + path)).default

        state.PageComponent = markRaw(Component)
      }
    }

    watch(() => navigator.state.route.path, utils.reset, { immediate: true })

    return () => {
      const { PageComponent } = state

      return (
        <div class="app-navigator-page">
          {!!PageComponent ? <PageComponent /> : null}
        </div>
      )
    }
  }
})
